import { ValidationError } from '@nestjs/common';
import { AppError, ErrorCodes } from '.';

export function transValidationError(errors: ValidationError[]) {
   if (errors.some(e => e.constraints !== undefined && e.constraints.nameExisted !== undefined)) {
      return new AppError('name existed', ErrorCodes.DuplicateName);
   } else if (errors.some(e => e.constraints !== undefined && e.constraints.idExisted !== undefined)) {
      return new AppError('id existed', ErrorCodes.DuplicateID);
   } else if (errors.some(e => e.constraints !== undefined && e.constraints.objectNotFound !== undefined)) {
      const feilds = errors.map(e => {
         if (e.constraints !== undefined && e.constraints.objectNotFound !== undefined) {
            return `${e.property}: ${e.value}`;
         }
      }).filter(e => e).join(', ');
      return new AppError(`${feilds} not found`, ErrorCodes.ObjectNotFound);
   } else if (errors.some(e => e.constraints !== undefined && e.constraints.isDefined !== undefined)) {
      const feilds = errors.map(e => {
         if (e.constraints !== undefined && e.constraints.isDefined !== undefined) {
            return e.property;
         }
      }).filter(e => e).join(', ');
      return new AppError(`${feilds} is not defined`, ErrorCodes.FieldRequired);
   } else if (errors.some(e => e.constraints !== undefined && e.constraints.whitelistValidation !== undefined)) {
      const feilds = errors.map(e => {
         if (e.constraints !== undefined && e.constraints.whitelistValidation !== undefined) {
            return e.property;
         }
      }).filter(e => e).join(', ');
      return new AppError(`${feilds} should not exist`, ErrorCodes.ValidationError);
   }
   return new AppError(errors, ErrorCodes.ValidationError);
}
